const inquirer = require('inquirer')
const utils = require('./utils')
const path = require('path')
const cmd = require('child_process')
const ora = require('ora')
let loading = ora()

// child_process.exec 所需的参数，避免 maxBuffer 不足而导致错误
const execOption = {
        encoding: 'utf8',
        timeout: 0,
        maxBuffer: 1000 * 1024 * 1024, // 默认 200 * 1024
        killSignal: 'SIGTERM'
    }

/*
 * 针对 XYMainApp 项目，拉取最新代码后，快速编译项目中的子工程
 * pods 在主工程下，target 在各自的子项目文件夹中
 * 注意：需要在 XYMainApp 项目路径下执行~~~
 *
 * 原始方式：podfile 中引入的 taregt，都需要对 Pods-target 与 target 各自编译一次，同时还区分真机与模拟器，比较费时间
 * 期望：自动一键编辑
 */
async function buildProject() {
    try {
        let params = await configBuildParams()
        let mainAppPath = params.mainApp
        // 主工程 pods 
        let podsProject = path.join(mainAppPath, 'Pods/Pods.xcodeproj')

        for (const index in params.list) {
            let element = params.list[index]
            // 独立 target (如：XYECommerce-Public/XYECommerce_Public.xcodeproj，文件是横线连接)
            let targetFolder = element.replace('_', '-')
            let targetProject = path.resolve(mainAppPath, '../', `${targetFolder}/${element}.xcodeproj`)

            // 编译 pods
            // await buildAction(podsProject, `Pods-${element}`, 'iphonesimulator', params.savePath)
            // await buildAction(podsProject, `Pods-${element}`, 'iphoneos', params.savePath)
            // 编译 target  目前不成功（除了 XYECommerce_Public）
            await buildAction(targetProject, element, 'iphonesimulator', params.savePath)
            await buildAction(targetProject, element, 'iphoneos', params.savePath)
        }
    } catch (error) {
        console.log(error)
    }
}

/*
 * 配置编译基本信息
 */
function configBuildParams() {
    const promptList = [
        {
            type: 'input',
            name: 'mainApp',
            message: 'XYMainApp 项目路径',
            default: process.cwd()
        },
        {
            type: "checkbox",
            message: "选择编译的子工程:",
            name: "list",
            choices: [
                "XYECommerce_Public",
                "XYECommerce",
                "XYECommerce_Customer",
                "XYECommerce_Data",
                "XYECommerce_Goods",
                "XYECommerce_GroupBuy",
                "XYECommerce_Market",
                "XYECommerce_Transaction",
                "XYCustomerIM"
            ]
        },
        {
            type: 'input',
            name: 'savePath',
            message: 'build 后产物存放路径？'
        }
    ]
    return new Promise((resolve, reject) => {
        inquirer.prompt(promptList)
            .then(answer => {
                resolve(answer)
            })
    })
}

/*
 * 编译
 */
function buildAction(project, target, sdk, buildDir) {
    loading.text = `build ${target} ${sdk}...`
    loading.start()
    let build_cmd = `xcodebuild build -project ${project} -target ${target} ONLY_ACTIVE_ARCH=NO -configuration Debug -sdk ${sdk} BUILD_DIR=${buildDir}`
    return new Promise((resolve, reject) => {
        cmd.exec(build_cmd, execOption, (err, stdout) => {
            loading.stop()
            if (err) {
                return reject(err)
            }
            utils.printSuccessLog(`build ${target} ${sdk} succeeded`)
            resolve()
        })
    })
}

module.exports = buildProject;